package cn.edu.ccut.refactor;

import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;

/**
 * 
 * @author Bai Yucheng 2008-1-23
 * 
 */
public class FileFilter extends ViewerFilter {
	private String fName;
	
	public FileFilter(String str) {
		fName = str;
	}
	
	public boolean select(Viewer viewer, Object parent, Object element) {
		 if (element instanceof IFolder) {
			IFolder folder = (IFolder) element;
			String name = folder.getName();
			IJavaElement javaElement = JavaCore.create(folder);
			if (javaElement == null) {
				return false;
			} else{
				if(javaElement.getElementType() == 3) {
					return true;
				} else if(javaElement.getElementType() == 4) {
					return canComplete(name, fName);
				} else {
					return false;
				}
			}
		} else if (element instanceof IContainer) { // IProject, IFolder
			try {
				IResource[] resources= ( (IContainer)element).members();
				for (int i= 0; i < resources.length; i++) {
					// recursive! Only show containers that contain a matching file
					if (select(viewer, parent, resources[i]) ) {
						return true;
					}
				}
			} catch (CoreException e) {
	
			}				
		}
		return false;
	}
		
	private boolean canComplete(String str1, String str2) {
		if (str2.matches(".*(action|logic|component|validate|data|workflow|web|page|Action|Logic|Component|Validate|Data|Workflow|Web|Page)")) { 
			if (str1.endsWith("action") || str1.endsWith("Action")) {  
				return str2.endsWith("action") || str2.endsWith("Action");  
			} else if (str1.endsWith("logic") || str1.endsWith("Logic")) {  
				return str2.endsWith("logic") || str2.endsWith("Logic");  
			} else if (str1.endsWith("component") || str1.endsWith("Component")) {  
				return str2.endsWith("component") || str2.endsWith("Component");  
			} else if (str1.endsWith("validate") || str1.endsWith("Validate")) {  
				return str2.endsWith("validate") || str2.endsWith("Validate");  
			} else if (str1.endsWith("data") || str1.endsWith("Data")) {  
				return str2.endsWith("data") || str2.endsWith("Data");  
			} else if (str1.endsWith("workflow") || str1.endsWith("Workflow")) {  
				return str2.endsWith("workflow") || str2.endsWith("Workflow");  
			} else if (str1.endsWith("web") || str1.endsWith("Web")) {  
				return str2.endsWith("web") || str2.endsWith("Web");  
			} else if (str1.endsWith("page") || str1.endsWith("Page")) {  
				return str2.endsWith("page") || str2.endsWith("Page");  
			} else if (str1.endsWith("module") || str1.endsWith("Module")) {  
				return true;
			}
		}
		return false;
	}
}

